//
//  NotificationTool.swift
//  LeGou
//
//  Created by lxm on 2022/10/18.
//

import Foundation

class NotificationTool {
    static let shard = NotificationTool()
    
    var requests = [UNNotificationRequest]()
    
    init() {
        getNotification()
    }
    
    // 请求授权
    func requestAuthorization(options : UNAuthorizationOptions = [.alert, .sound, .badge], completionHandler :  @escaping (Bool, Error?) -> Void) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: options, completionHandler: completionHandler)
    }
    
    /// 添加通知
    /// - Parameters:
    ///   - identifier: 标识
    ///   - timeInterval: 倒计时多久
    func addNotifaction(identifier : String, timeInterval : Double, title : String, subtitle : String, body : String) {
        let no = UNMutableNotificationContent()
        no.title = title
        no.subtitle = subtitle
        no.body = body
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
        let notification = UNNotificationRequest.init(identifier: identifier, content: no, trigger: trigger)
        UNUserNotificationCenter.current().add(notification) { e in
            if e != nil {
                XMLogger.info("添加通知失败")
            } else {
                XMLogger.info("添加 \(identifier) 成功")
                self.getNotification()
            }
        }
    }
    
    func getNotification(_ complete : (()->())? = nil) {
        UNUserNotificationCenter.current().getPendingNotificationRequests { r in
            self.requests = r
            if let complete = complete {
                complete()
            }
            self.logInfo(identifier: nil)
        }
    }
    
    /// 检查对应标识通知是否存在
    /// - Parameter identifier:
    /// - Returns:
    func checkNotificationExist(_ identifier : String) -> Bool {
        if identifier.count == 0 {
            return false
        }
        logInfo(identifier: identifier)
        let r = requests.contains(where: {$0.identifier == identifier})
        return r
    }
    
    func logInfo(identifier : String?) {
        XMLogger.tracking("requests ：")
        for m in requests {
            XMLogger.tracking("identifier:\(m.identifier)")
        }
        if let identifier = identifier {
            XMLogger.tracking("当前比较的 identifier ： \(identifier)")
        }
    }
    
    func cancelNotification(_ identifier : String) {
        let center = UNUserNotificationCenter.current()
        center.removePendingNotificationRequests(withIdentifiers: [identifier])
        getNotification()
    }
}
